import { List, message, Skeleton, Spin, Space } from 'antd';
import { DownOutlined, StarOutlined, LikeOutlined, MessageOutlined } from '@ant-design/icons';
import React from 'react'
import reqwest from 'reqwest';
import { Link } from 'umi';

import WindowScroller from 'react-virtualized/dist/commonjs/WindowScroller';
import AutoSizer from 'react-virtualized/dist/commonjs/AutoSizer';
import VList from 'react-virtualized/dist/commonjs/List';
import InfiniteLoader from 'react-virtualized/dist/commonjs/InfiniteLoader';

import styles from './index.less'

// 模拟接口地址
// const fakeDataUrl = 'https://120.76.193.53/app/mock/data/2060786?scope=response';
const fakeDataUrl = 'https://120.76.193.53/app/mock/data/2060786?scope=response';

const IconText = ({ icon, text }) => (
  <Space>
    {React.createElement(icon)}
    {text}
  </Space>
);

class ArticleList extends React.Component {

  state = {
    data: [],
    loading: true,
    firstLoding: true
  };

  loadedRowsMap = {};

  // 初始化加载时获取一次数据
  componentDidMount() { 
    this.fetchData(res => {
      this.setState({ firstLoding: false })
      this.setState({
        data: res.results,
      });
    });
  }


  // 接口调用获取数据
  fetchData = callback => {
    reqwest({
      url: fakeDataUrl,
      type: 'json',
      method: 'get',
      contentType: 'application/json',
      success: res => {
        callback(res);
      },
    });
  };

  // 处理数据加载
  handleInfiniteOnLoad = ({ startIndex, stopIndex }) => {

    let { data } = this.state;

    // 设置Loading
    this.setState({
      loading: true,
    });

    for (let i = startIndex; i <= stopIndex; i++) {
      // 1 means loading
      this.loadedRowsMap[i] = 1;
    }

    // 判断数据条数，超过最大值就不获取数据了
    if (data.length > 100) {
      message.warning('没有更多啦！');
      this.setState({
        loading: false,
      });
      return;
    }

    // 获取数据
    this.fetchData(res => {
      data = data.concat(res.results);
      this.setState({
        data,
        loading: false,
      });
    });
  };

  isRowLoaded = ({ index }) => !!this.loadedRowsMap[index];


  readAll = (showReadAll) => {
    if (showReadAll) {
      return (
        <span style={{ color: '#5582F3', marginLeft: 4, }}>
          阅读全文< DownOutlined style={{ fontSize: 12, marginLeft: 4 }} />
        </span>
      )
    }
  }

  renderItem = ({ index, key, style }) => {
    const { data } = this.state;
    const item = data[index];

    const handleClick = () => {
      const url = `/article/${item.id}`
      this.props.history.push(url)
    }

    return (
      <List.Item key={key} style={style}>
        <div style={{ height: '100%', display: 'flex', flexDirection: 'column', justifyContent: 'space-between', }}>
          <h2 className={styles["ContentItem-title"]} style={{ display: 'block', marginBottom: 0 }}>
            <Link
              to={`/article/${item.id}`}
              style={{
                color: 'inherit',
                fontSize: 20,
                fontWeight: 600
              }}
            // href={`/article/${item.id}`}
            // target="_self"
            // rel="noopener noreferrer"
            >
              {item.title}
            </Link>
          </h2>

          <span style={{ color: '#808080', fontSize: 13, display: 'block', cursor: 'default' }}>{item.createTime}</span>

          <div className={styles["ContentItem-content"]} style={{ display: 'flex', lineHeight: 1.67, cursor: 'pointer' }} onClick={handleClick}>
            <div className={styles["richContentCover"]}>
              <img
                alt="logo"
                src={item.cover}
                className={styles["coverImage"]}
              />
            </div>

            <div className={styles["RichContent-inner"]} style={{ paddingTop: 5, paddingBottom: 5 }}>
              <span className={styles["content-span"]} >
                <span dangerouslySetInnerHTML={{ __html: `${item.content}` }} />
              </span>
            </div>
          </div>


          <div className={styles["ContentItem-actions"]} style={{ float: 'inline-end', marginTop: 8, cursor: 'pointer' }}>
            赞同{item.up}​ ​{item.comment}条评论 分享 收藏 举报
            <span style={{ color: '#5582F3', marginLeft: 4, float: 'right' }} onClick={handleClick}>
              阅读全文< DownOutlined style={{ fontSize: 12, marginLeft: 4 }} />
            </span>
          </div>
        </div>
        {/* </Skeleton> */}
      </List.Item >
    );
  };

  render() {
    const { data } = this.state;
    const vlist = ({ height, isScrolling, onChildScroll, scrollTop, onRowsRendered, width }) => (
      <VList
        autoHeight
        height={height}
        isScrolling={isScrolling}
        onScroll={onChildScroll}
        overscanRowCount={10}
        rowCount={data.length}
        rowHeight={230}
        rowRenderer={this.renderItem}
        onRowsRendered={onRowsRendered}
        scrollTop={scrollTop}
        width={width}
      />
    );
    const autoSize = ({ height, isScrolling, onChildScroll, scrollTop, onRowsRendered }) => (
      <AutoSizer disableHeight>
        {({ width }) =>
          vlist({
            height,
            isScrolling,
            onChildScroll,
            scrollTop,
            onRowsRendered,
            width,
          })
        }
      </AutoSizer>
    );
    const infiniteLoader = ({ height, isScrolling, onChildScroll, scrollTop }) => (
      <InfiniteLoader
        isRowLoaded={this.isRowLoaded}
        loadMoreRows={this.handleInfiniteOnLoad}
        rowCount={data.length}
      >
        {({ onRowsRendered }) =>
          autoSize({
            height,
            isScrolling,
            onChildScroll,
            scrollTop,
            onRowsRendered,
          })
        }
      </InfiniteLoader>
    );
    return (
      <div>
        <List size="large" itemLayout="vertical" loading={this.state.firstLoding}>
          {data.length > 0 && <WindowScroller>{infiniteLoader}</WindowScroller>}
          {this.state.loading && <Spin className={styles["demo-loading"]} />}
          <div style={{ padding: 20 }}>
            <Skeleton loading={this.state.firstLoding} active />
          </div>
        </List>
      </div>
    );
  }
}

export default ArticleList